<template>
  <div class="system-settings-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/system' }">系统管理</el-breadcrumb-item>
        <el-breadcrumb-item>系统设置</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    
    <!-- 主要内容区 -->
    <div class="main-content">
      <!-- 功能选项卡 -->
      <el-tabs v-model="activeTab" type="border-card" class="settings-tabs">
        <!-- 所有配置 -->
        <el-tab-pane label="所有配置" name="allConfigs">
          <div class="tab-content">
            <!-- 工具栏 -->
            <div class="toolbar">
              <!-- 搜索区域容器，让搜索框和按钮靠近 -->
              <div class="search-group">
                <el-input 
                  v-model="searchKeyword" 
                  placeholder="搜索配置项" 
                  prefix-icon="Search"
                  class="search-input"
                />
                <el-button class="search-btn" type="primary" @click="searchConfig">搜索</el-button>
              </div>
              <!-- 工具栏操作区，居右 -->
              <div class="toolbar-actions">
                <el-button type="primary" @click="refreshCache">刷新</el-button>
              </div>
            </div>
            
            <!-- 配置表格 -->
            <el-table 
              :data="configEnity" 
              border 
              class="config-table"
              v-loading="false"
            >
              <el-table-column prop="configKey" label="配置键" width="120" sortable align="center" />
              <el-table-column prop="configValue" v-model="configDeatil.configValue" label="配置值" min-width="90" align="center"  />
              <el-table-column prop="configDesc" label="描述" min-width="150" align="center" />
              <el-table-column label="操作"  align="center" >
                <template #default="scope">
                  <el-button size="small" type="primary" @click="dialogVisible=true,getConfigDetail(scope.row.id)">编辑</el-button>
                  <el-button size="small" type="info" @click="config_key = scope.row.configKey; activeTab = 'configHistory'; getConfigHistory()">历史</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        
        <!---公共配置--->
        <el-tab-pane label="公共配置项" name="publicConfigs">
          <div class="tab-content">
            <el-card>
              <div class="public-config-header">
                <h3>公共配置信息</h3>
                <el-button 
                  size="small" 
                  type="primary" 
                  @click="getCommonConfig"
                >
                  刷新
                </el-button>
              </div>
              
              <!-- 配置内容展示 -->
              <el-descriptions 
                border 
                class="public-configs"
                column="2"
              >
                <el-descriptions-item 
                  v-for="item in getPublicConfigList" 
                  :key="item.id" 
                  :label="item.configDesc"
                >
                  <span 
                    :class="item.configValue === 'true' ? 'text-success' : 'text-danger'"
                  >
                    {{ item.configValue}}
                  </span>
                </el-descriptions-item>
                
                <!-- 空状态处理 -->
                <div v-if="getPublicConfigList.length === 0 && !loadingPublicConfig" class="empty-state">
                  <el-empty description="暂无公共配置数据"></el-empty>
                </div>
              </el-descriptions>
            </el-card>
          </div>
        </el-tab-pane>

        <!-- 配置历史 -->
        <el-tab-pane label="配置历史" name="configHistory">
          <div class="tab-content">
            <!-- 查询区域 -->
            <el-card class="search-card">
              <el-form inline>
                <el-form-item label="配置键">
                  <el-input v-model="config_key" placeholder="请输入配置键" />
                </el-form-item>
            
                <el-form-item label="配置人">
                  <el-input v-model="operator_id" placeholder="请输入配置人id" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="getConfigHistory()" >查询</el-button>
                  <el-button @click="resetSearchForm()">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
            
            <!-- 历史记录表格 -->
            <el-table 
              :data="getConfigHistoryList" 
              border 
              class="history-table"
              style="margin-top: 16px;"
            >
              <el-table-column prop="configKey" label="配置键" width="100" align="center" />
              <el-table-column prop="oldValue" label="旧值" min-width="120" align="center" />
              <el-table-column prop="newValue" label="新值" min-width="120" align="center" />
              <el-table-column prop="operatorId" label="操作人" width="90" align="center" />
              <el-table-column prop="createdTime" label="操作时间" sortable align="center">
                <template #default="scope">
                  {{ formatDateTime(scope.row.createdTime) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <!-- 编辑配置对话框 -->
    <el-dialog 
      title="编辑配置" 
      v-model="dialogVisible" 
      width="600px"
    >
      <el-form 
        :model="configDeatil" 
        label-width="120px"
      >
        <el-form-item label="配置键">
          <el-input disabled  v-model="configDeatil.configKey" />
        </el-form-item>
        
        <el-form-item label="配置值" required>
          <el-input 
            placeholder="请输入配置值"
            type="textarea"
            rows="1"
            v-model="configDeatil.configValue"
          />
        </el-form-item>
        
        <el-form-item label="配置描述">
          <el-input 
            disabled
            v-model="configDeatil.configDesc"
          />
        </el-form-item>
 
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateConfig(configDeatil.id,configDeatil.configValue)">保存修改</el-button>
      </template>
    </el-dialog>
    
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { onMounted } from 'vue';
import { configAPI } from '../../api/config';
import { ElMessage } from 'element-plus';
const configEnity=ref([]);
const getPublicConfigList=ref([]);

const page=ref(1);
const pageSize=ref(10);
const config_key=ref('');
const operator_id=ref('');

const getConfigHistoryList=ref([]);

const configDeatil=ref({
    id:'',
    configKey:'',
    configValue:'',
    configDesc:''
})

//获取所有系统配置
const getConfigList=async()=>{
    try{
        const res=await configAPI.getConfigList();
        configEnity.value=res.data;
    }catch(error){
       ElMessage.error(error.message);
    }
}

//刷新缓存
const refreshCache=async()=>{
    try{
        const res=await configAPI.refreshCache();
        getConfigList();
        ElMessage.success('刷新缓存成功');
    }catch(error){
       ElMessage.error(error.message);
    }
}

//获取公共配置信息
const getCommonConfig=async()=>{
    try{
        const res=await configAPI.getCommonConfig();
        getPublicConfigList.value=res.data;
    }catch(error){
       ElMessage.error(error.message);
    }
}

//获取配置历史
const getConfigHistory=async()=>{
    try{
        const res=await configAPI.getConfigHistory(config_key.value, operator_id.value, page.value, pageSize.value);
        getConfigHistoryList.value=res.data;
    }catch(error){
       ElMessage.error(error.message);
    }
}

//更新配置
const updateConfig=async()=>{ 
    try{
        const res=await configAPI.updateConfig(configDeatil.value.id,configDeatil.value.configValue);
        dialogVisible.value=false;
        refreshCache();
        getConfigList();
        ElMessage.success(res.message);
    }catch(error){
       ElMessage.error(error.message);
    }
}

//获取配置详情
const getConfigDetail=async(id)=>{ 
    try{
        const res=await configAPI.getConfigDetail(id);
        configDeatil.value = res.data;
        dialogVisible.value=true;
    }catch(error){
       ElMessage.error(error.message);
    }
}

//重置搜索表单
const resetSearchForm=()=>{ 
    config_key.value='';
    operator_id.value='';
    getConfigHistory();
}

//查询配置
const searchConfig=async()=>{ 
    try{
        const res=await configAPI.searchConfig(searchKeyword.value);
        configEnity.value=res.data;
    }catch(error){
       ElMessage.error(error.message);
    }
}

// 时间格式化函数
const formatDateTime = (dateString) => {
  if (!dateString) return '';  
  const date = new Date(dateString);
  if (isNaN(date.getTime())) return dateString;  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); 
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

onMounted(()=>{
  getConfigList();
  getCommonConfig();
  getConfigHistory(config_key.value,operator_id.value,page.value,pageSize.value);
})

// 状态管理
const activeTab = ref('allConfigs');
const searchKeyword = ref('');
const dialogVisible = ref(false);
</script>

<style scoped>
.system-settings-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  margin: 10px 0 0;
  font-size: 20px;
  color: #1f2329;
}

.main-content {
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 20px;
}

.settings-tabs {
  width: 100%;
}

.tab-content {
  padding: 16px 0;
}

/* 工具栏样式调整 */
.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between; /* 让搜索组和操作区分开 */
  margin-bottom: 16px;
}

/* 搜索区域容器，让输入框和按钮贴近 */
.search-group {
  display: flex;
  align-items: center;
  gap: 8px; /* 控制搜索框和按钮间距 */
}

.search-input {
  width: 300px;
}

.search-btn {
  white-space: nowrap; /* 防止按钮文字换行 */
}

/* 工具栏操作区，居右 */
.toolbar-actions {
  display: flex;
  gap: 10px;
}

/* 表格样式 */
.config-table, .history-table {
  width: 100%;
}

.details-table {
  width: 100%;
  margin-top: 16px;
}

/* 分页样式 */
.pagination {
  margin-top: 16px;
  text-align: right;
}

/* 缓存卡片样式 */
.cache-card {
  max-width: 900px;
  margin: 0 auto;
}

.cache-overview {
  margin-bottom: 24px;
}

.cache-stats {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  gap: 16px;
  margin-top: 16px;
}

.stat-item {
  flex: 1;
  min-width: 200px;
  text-align: center;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.stat-label {
  display: block;
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.stat-value {
  display: block;
  font-size: 22px;
  font-weight: 600;
  color: #1890ff;
}

.cache-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-bottom: 24px;
}

.cache-details {
  margin-top: 24px;
}

/* 公共配置样式 */
.public-config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.public-configs {
  margin-top: 16px;
}

/* 表单样式 */
.form-title {
  margin: 0 0 16px;
  font-size: 16px;
  color: #1f2329;
}

.config-form {
  margin-top: 16px;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 16px;
}
</style>